package com.hmsg.health.utils;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import org.apache.commons.lang3.math.NumberUtils;


/**
 * 
 * @author lujq
 *
 */
public class StringUtil {

	private StringUtil() {
	}

	public static boolean isEmpty(String str) {
		return str == null || str.length() == 0 || ConstantUtil.EMPTY_VALUE.equals(str.trim());
	}

	public static boolean isNotEmpty(String str) {
		return !isEmpty(str);
	}

	/**
	 * 判断字符串是否为数字
	 */
	public static boolean isNumeric(String str) {
		return NumberUtils.isDigits(str);
	}

	/**
	 * 拼接字符串
	 * 
	 * @param split
	 * @param values
	 * @return
	 */
	public static String concat(String split, String... values) {
		StringBuilder builder = new StringBuilder();
		for (String s : values) {
			builder.append(s).append(split);
		}
		if (!isEmpty(split)) {
			builder.deleteCharAt(builder.length() - 1);
		}
		return builder.toString();
	}

	/**
	 * 统计字符串出现的次数
	 * 
	 * @param str
	 * @param sub
	 * @return
	 */
	public static int countMatches(String str, String sub) {
		if (str == null || str.length() == 0 || sub == null || sub.length() == 0)
			return 0;
		int count = 0;
		for (int idx = 0; (idx = str.indexOf(sub, idx)) != -1; idx += sub.length())
			count++;

		return count;
	}

	/**
	 * org.apache.commons.lang3
	 * <p>
	 * Gets the String that is nested in between two instances of the same
	 * String.
	 * </p>
	 * <p>
	 * A {@code null} input String returns {@code null}. A {@code null} tag
	 * returns {@code null}.
	 * </p>
	 *
	 * <pre>
	 * StringUtils.substringBetween(null, *)            = null
	 * StringUtils.substringBetween("", "")             = ""
	 * StringUtils.substringBetween("", "tag")          = null
	 * StringUtils.substringBetween("tagabctag", null)  = null
	 * StringUtils.substringBetween("tagabctag", "")    = ""
	 * StringUtils.substringBetween("tagabctag", "tag") = "abc"
	 * </pre>
	 *
	 * @param str
	 *            the String containing the substring, may be null
	 * @param tag
	 *            the String before and after the substring, may be null
	 * @return the substring, {@code null} if no match
	 * @since 2.0
	 */
	public static String substringBetween(String str, String tag) {
		return substringBetween(str, tag, tag);
	}

	public static String substringBetween(String str, String open, String close) {
		if (str == null || open == null || close == null)
			return null;
		int start = str.indexOf(open);
		if (start != -1) {
			int end = str.indexOf(close, start + open.length());
			if (end != -1)
				return str.substring(start + open.length(), end);
		}
		return null;
	}

	/**
	 * 删除最后一个字符
	 * 
	 * @param builder
	 * @param tag
	 * @return
	 */
	public static StringBuilder deleteEndTag(StringBuilder builder, String tag) {
		if (builder != null) {
			if (builder.toString().endsWith(tag)) {
				builder.deleteCharAt(builder.length() - 1);
			}
		}
		return builder;
	}

	/**
	 * 批量替换内容
	 * 
	 * @param map
	 * @param text
	 * @return
	 */
	public static String replaceMap(Map<String, String> map, String text) {
		for (Entry<String, String> entry : map.entrySet()) {
			if (!isEmpty(entry.getKey())) {
				text = text.replace(entry.getKey(), entry.getValue());
			}
		}
		return text;
	}

	/**
	 * 字符串转list
	 * 
	 * @param str
	 * @return
	 */
	public static List<Integer> strToList(String str) {
		if (isEmpty(str)) {
			return new LinkedList<Integer>();
		}
		List<Integer> integers = new LinkedList<Integer>();
		String[] strs = str.replaceAll("[\\s()\\[\\]]", "").split(",");
		for (int i = 0; i < strs.length; i++) {
			integers.add(Integer.parseInt(strs[i]));
		}
		return integers;
	}

	/**
	 * 压缩字符串
	 * 
	 * @param str
	 * @return
	 */
	public static String compressToStr(String str) {
		return new String(compress(str));
	}

	public static byte[] compress(String str) {
		try {
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream);

			byte[] bytes = str.getBytes(ConstantUtil.UTF_8);
			gzipOutputStream.write(bytes, 0, bytes.length);
			gzipOutputStream.finish();
			gzipOutputStream.flush();
			gzipOutputStream.close();

			return byteArrayOutputStream.toByteArray();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 解压缩字符串
	 * 
	 * @param str
	 * @return
	 */
	public static String decompress(String str) {
		return new String(decompress(str.getBytes()));
	}

	public static String decompress(byte[] bytes) {
		try {
			GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(bytes));
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(gzipInputStream, ConstantUtil.UTF_8));

			StringBuffer content = new StringBuffer();
			String line;
			while ((line = bufferedReader.readLine()) != null) {
				content.append(line);
			}

			return content.toString();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static <T> String convertMapToParameter(Map<String, String[]> map) {
		if (map.isEmpty()) {
			return "";
		}
		StringBuilder parameterUrl = new StringBuilder();
		if (!map.isEmpty()) {
			for (Entry<String, String[]> entry : map.entrySet()) {
				parameterUrl.append(entry.getKey()).append("=").append(entry.getValue() == null ? "" : entry.getValue()[0]).append("&");
			}
		}
		return parameterUrl.toString();

	}
}
